class MyPromise {
  constructor(executor) {
    this.state = 'pending'  // 'fulfilled'   'rejected' 
    this.value = undefined
    this.reason = undefined
    this.onFulfilledCallbacks = []  // 接受then中的回调
    this.onRejectedCallbacks = []   // catch中的回调


    const resolve = (value) => {
      if (this.state === 'pending') {
        this.state = 'fulfilled'
        this.value = value
        this.onFulfilledCallbacks.forEach(callback => callback(value))
      }
    }
    const reject = (reason) => {
      if (this.state = 'pending') {
        this.state = 'rejected'
        this.reason = reason
        this.onRejectedCallbacks.forEach(callback => callback(reason))
      }
    }


    executor(resolve, reject)
  }

  then(onFulfilled, onRejected) {
    onFulfilled = typeof onFulfilled == 'function' ? onFulfilled : (value) => value
    onRejected = typeof onRejected == 'function' ? onRejected : (reason) => { throw reason }

    
    const newPromise = new MyPromise((resolve, reject) => {
      // then前面的promise状态已经是 fulfilled
      if (this.state === 'fulfilled') {
        // 将 onFulfilled() 推入到微任务队列
        setTimeout(() => {
          try {
            const result = onFulfilled(this.value)
            resolve(result)
          } catch (error) {
            reject(error)
          }
        })
      }
      if (this.state === 'rejected') {
        setTimeout(() => {
          try {
            const result = onRejected(this.value)
            resolve(result)
          } catch (error) {
            reject(error)
          }
        })
      }

      // 将 onFulfilled, onRejected 保存进数组
      if (this.state === 'pending') {
        this.onFulfilledCallbacks.push((value) => {
          setTimeout(() => {
            try {
              const result = onFulfilled(value)
              resolve(result)
            } catch (error) {
              reject(error)
            }
          })
        })

        this.onRejectedCallbacks.push((value) => {
          setTimeout(() => {
            try {
              const result = onRejected(value)
              resolve(result)
            } catch (error) {
              reject(error)
            }
          })
        })

      }


    })

    return newPromise

  }

  static all(promises) {
    return new MyPromise((resolve, reject) => {
      // promises数组中所有的promise状态都变更为 fulfilled 才调用自己的 resolve()
      let count = 0
      let res = []

      for (let i = 0; i < promises.length; i++) {
        promises[i].then(
          (val) => {
            count++
            res[i] = val

            if (count === promises.length) {
              resolve(res)
            }
          },
          (reason) => {
            reject(reason)
          }
        )
      }


    })
  }

}



let p = new MyPromise((resolve, reject) => {
  // reject()
  resolve(1)
})
p
.then((res) => {
  console.log(res);
  
})
